package top.purity.framework.orm.jpa;

import cn.hutool.core.util.ObjUtil;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.context.spi.CurrentTenantIdentifierResolver;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.stereotype.Component;
import top.purity.framework.common.TenantContextHolder;

import java.util.Map;

/**
 * @version 1.0
 * @Author Lmh
 * @Description
 * @CreateTime 2023-10-28 21:00
 */
@Component
public class TenantResolver implements CurrentTenantIdentifierResolver<String>, HibernatePropertiesCustomizer {

    private static final String DEFAULT = "0";

    @Override
    public String resolveCurrentTenantIdentifier() {
        Long tenantId = TenantContextHolder.getTenantId();
        return ObjUtil.isNull(tenantId) ? DEFAULT:tenantId.toString();
    }

    @Override
    public boolean validateExistingCurrentSessions() {
        return true;
    }

    @Override
    public boolean isRoot(String tenantId) {
        return TenantContextHolder.isIgnore();
    }

    @Override
    public void customize(Map<String, Object> hibernateProperties) {
        hibernateProperties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this);
    }
}
